//CalculatorActivity
package com.aduerr.v1shouyin.mvp.activity;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.common.DatabaseManager;
import com.aduerr.v1shouyin.entity.CashEntity;
import com.aduerr.v1shouyin.entity.GetUnionOrderEntity;
import com.aduerr.v1shouyin.entity.OrderRecordEntity;
import com.aduerr.v1shouyin.entity.UpdateUnionPayOrderStateEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.unioncard.UnionSignInActivity;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.MessageEvent;
import com.aduerr.v1shouyin.util.NumUtil;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.CalculatorEditText;
import com.aduerr.v1shouyin.view.CalculatorExpressionBuilder;
import com.aduerr.v1shouyin.view.CalculatorExpressionEvaluator;
import com.aduerr.v1shouyin.view.CalculatorExpressionTokenizer;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.action.PosSign;
import com.yeahka.shouyintong.sdk.action.SwipeCardTrans;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;
import com.yeahka.shouyintong.sdk.excep.ActionIllegalException;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import cn.pedant.SweetAlert.SweetAlertDialog;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

import static java.lang.Double.parseDouble;

public class CalculatorActivity extends Activity
        implements CalculatorEditText.OnTextSizeChangeListener,
        CalculatorExpressionEvaluator.EvaluateCallback, View.OnLongClickListener,
        View.OnClickListener {

    public static final String TAG = "CalculatorActivity";
    /**
     * Constant for an invalid resource id.
     */
    public static final int INVALID_RES_ID = -1;
    public static final int NO_CASH = 5, CASH = 6;//NO_CASH :扫码，会员等，CASH：现金记账；
    private static final String NAME = CalculatorActivity.class.getName();
    // instance state keys
    private static final String KEY_CURRENT_STATE = NAME + "_currentState";
    private static final String KEY_CURRENT_EXPRESSION = NAME + "_currentExpression";
    private String globalOrderid;
    private RelativeLayout rl_shaoma;
    private RelativeLayout rl_member;
    private RelativeLayout rl_union;
    private Button btCashPay;
    private LinearLayout llPayType;
    private CalculatorState mCurrentState;
    private CalculatorExpressionTokenizer mTokenizer;
    private final Editable.Factory mFormulaEditableFactory = new Editable.Factory() {
        @Override
        public Editable newEditable(CharSequence source) {
            final boolean isEdited = mCurrentState == CalculatorState.INPUT
                    || mCurrentState == CalculatorState.ERROR;
            return new CalculatorExpressionBuilder(source, mTokenizer, isEdited);
        }
    };
    private CalculatorExpressionEvaluator mEvaluator;

    private CalculatorEditText mFormulaEditText;
    private CalculatorEditText mResultEditText;
    private View mDeleteButton;
    private View mClearButton;
    private final TextWatcher mFormulaTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int count,
                                  int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            setState(CalculatorState.INPUT);
            mEvaluator.evaluate(editable, CalculatorActivity.this);
        }
    };
    private final View.OnKeyListener mFormulaOnKeyListener =
            (view, keyCode, keyEvent) -> {
        switch(keyCode) {
            case KeyEvent.KEYCODE_NUMPAD_ENTER:
            case KeyEvent.KEYCODE_ENTER:
                if(keyEvent.getAction() == KeyEvent.ACTION_UP) {
                    onEquals();
                }
                // ignore all other actions
                return true;
        }
        return false;
    };
    private View mEqualButton;
    private Animator mCurrentAnimator;
    private SweetAlertDialog pDialog;
    private ImageView ivQRCode, ivBack;
    private TextView tvTitle;
    private EditText etMark;
    private LinearLayout llMark;
    private int flag = 0; //监听输入法事件要用的的参数
    private View ivMask;
    private String num = "";

    private SytApi sytApi;

    BroadcastReceiver broadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action, Constants.ACTION)) {
                try {
                    sytApi.handleAction(intent, baseResp -> {
                        if(baseResp.isSuccessful()) {
                            if(baseResp instanceof PosSign.Resp) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Hawk.put("signTime", sdf.format(new Date()));
                                Hawk.put("unionMerchantId", ((PosSign.Resp) baseResp).merchantId);
                                //签到
                                Intent intentSign = new Intent(CalculatorActivity.this,
                                        UnionSignInActivity.class);
                                intentSign.putExtra("resp", baseResp);
                                startActivity(intentSign);
                            } else if(baseResp instanceof SwipeCardTrans.Resp) {
                                //刷卡
                                onClear();
                                ToastUtils.showToast(CalculatorActivity.this, "交易成功");
                            }
                        } else {
                            if(baseResp instanceof SwipeCardTrans.Resp) {
                                if(TextUtils.equals(((SwipeCardTrans.Resp) baseResp).tradeInfo.getAnswerCode(), "B2")) {
                                    ToastUtils.showToast(CalculatorActivity.this, "状态异常，签到后再进行操作");
                                    sign();
                                } else {
                                    ToastUtils.showToast(CalculatorActivity.this,
                                            baseResp.getMsg() + "，" + baseResp.getCode());
                                }
                            }
                        }
                    });
                } catch(ActionIllegalException e) {
                    e.printStackTrace();
                } catch(Exception e) {
                    Log.d("calcu", e.getMessage());
                    Log.d("calcu", e.getCause().toString());
                }
            }
        }

    };

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator_layout);
        initView(savedInstanceState);
        initEvent();

        sytApi = SytFactory.createSytIml(this);
        boolean installed = sytApi.isSytInstalled();
        if(!installed) {
            ToastUtils.showToast(this, "未安装收银台App，刷卡功能无法使用");
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION);
        registerReceiver(broadcastReceive, intentFilter);

        EventBus.getDefault().register(this);
    }

    private void initView(Bundle savedInstanceState) {
        Intent intent = getIntent();
        mFormulaEditText = (CalculatorEditText) findViewById(R.id.formula);
        //明细
        mResultEditText = (CalculatorEditText) findViewById(R.id.result);
        mDeleteButton = findViewById(R.id.del);
        mClearButton = findViewById(R.id.clr);
        ivQRCode = (ImageView) findViewById(R.id.iv_erweima);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack = (ImageView) findViewById(R.id.img_back);
        etMark = (EditText) findViewById(R.id.et_mark);
        llMark = (LinearLayout) findViewById(R.id.ll_mark);
        tvTitle.setText("收款");
        ivBack.setOnClickListener(this);
        ivMask = (View) findViewById(R.id.iv_mask);
        ivMask.setOnTouchListener((v, event) -> {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(ivMask.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            return true;
        });

        //===========================底部的4个控件事件======================================

        rl_shaoma = (RelativeLayout) findViewById(R.id.rl_shaoma);
        rl_member = (RelativeLayout) findViewById(R.id.rl_member);
        rl_union = (RelativeLayout) findViewById(R.id.rl_union);


        btCashPay = (Button) findViewById(R.id.bt_cash_pay);
        llPayType = (LinearLayout) findViewById(R.id.cal_top6_ll);

        if(intent.getIntExtra("CSAH_TYPE", -1) == NO_CASH) {
            btCashPay.setVisibility(View.GONE);
            llPayType.setVisibility(View.VISIBLE);
        } else if(intent.getIntExtra("CSAH_TYPE", -1) == CASH) {
            btCashPay.setVisibility(View.VISIBLE);
            llPayType.setVisibility(View.GONE);
        }

        //=====================计算器逻辑==================================================
        mEqualButton = findViewById(R.id.pad_numeric).findViewById(R.id.eq);
        if(mEqualButton == null || mEqualButton.getVisibility() != View.VISIBLE) {
            mEqualButton = findViewById(R.id.pad_numeric).findViewById(R.id.eq);
        }
        mTokenizer = new CalculatorExpressionTokenizer(this);
        mEvaluator = new CalculatorExpressionEvaluator(mTokenizer);
        savedInstanceState = savedInstanceState == null ? Bundle.EMPTY :
                savedInstanceState;
        setState(CalculatorState.values()[savedInstanceState.getInt(KEY_CURRENT_STATE,
                CalculatorState.INPUT.ordinal())]);
        mFormulaEditText.setText(mTokenizer.getLocalizedExpression(savedInstanceState.getString(KEY_CURRENT_EXPRESSION, "")));
        mEvaluator.evaluate(mFormulaEditText.getText(), this);
        mFormulaEditText.setEditableFactory(mFormulaEditableFactory);
        mFormulaEditText.addTextChangedListener(mFormulaTextWatcher);
        mFormulaEditText.setOnKeyListener(mFormulaOnKeyListener);
        mFormulaEditText.setOnTextSizeChangeListener(this);
        mDeleteButton.setOnLongClickListener(this);
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom
                    , int oldLeft, int oldTop, int oldRight, int oldBottom) {
                //获取View可见区域的bottom
                if(flag > 1) {
                    Rect rect = new Rect();
                    getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                    if(bottom != 0 && oldBottom != 0 && bottom - rect.bottom <= 0) {
                        //                        Toast.makeText(CalculatorActivity
                        //                        .this, "隐藏", Toast.LENGTH_SHORT).show();
                        ivMask.setVisibility(View.INVISIBLE);
                    } else {
                        //                        Toast.makeText(CalculatorActivity
                        //                        .this, "弹出", Toast.LENGTH_SHORT).show();
                        ivMask.setVisibility(View.VISIBLE);
                    }
                }
                flag++;
            }
        });

    }

    //初始化事件
    private void initEvent() {

        //=================================右上角的二维码===========================================
        ivQRCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String realMoneyResult = mResultEditText.getText().toString();
                String realMoneyDetail = mFormulaEditText.getText().toString();
                LogUtils.e("goToCashPay", realMoneyResult + "**" + realMoneyDetail);
                String realMoney = null;
                if(TextUtils.isEmpty(realMoneyDetail)) {
                    ToastUtils.showToast(CalculatorActivity.this, "请输入金额");
                    return;
                }

                //负数判断
                if(!realMoneyResult.matches("-?[0-9]+.*[0-9]*")) {
                    ToastUtils.showToast(CalculatorActivity.this, "请输入正确的金额");
                    return;
                }

                if(TextUtils.isEmpty(realMoneyResult)) {
                    if(realMoneyDetail.contains("+")) {
                        String replace = realMoneyDetail.replace("+", "");
                        realMoney = replace;
                    } else {
                        realMoney = realMoneyDetail;
                    }

                } else {
                    realMoney = realMoneyResult;
                }

                //大于0的判断
                Double intrealMoneyDetail = parseDouble(realMoney);
                if(intrealMoneyDetail < 0 | intrealMoneyDetail == 0) {
                    ToastUtils.showToast(CalculatorActivity.this, "输入金额必须大于0");
                    return;
                }
                Intent intent = new Intent(CalculatorActivity.this,
                        ErweimaActivity.class);
                intent.putExtra("beizhu", getMark());
                intent.putExtra("realymoney", intrealMoneyDetail + "");
                //获取计算器上的数据
                startActivity(intent);
            }
        });
        //底部的点击事件
        rl_shaoma.setOnClickListener(this);
        rl_member.setOnClickListener(this);
        rl_union.setOnClickListener(this);
        btCashPay.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.rl_shaoma:
                if(mResultEditText.getText().toString().contains("−") || mResultEditText.getText().toString().equals("0")) {
                    ToastUtils.showToast(this, "交易金额不能小于0");
                    return;
                }
                if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 1000000f) {
                    ToastUtils.showToast(this, "金额不能大于一百万");
                    //                    ToastUtils.showToast(this, String.valueOf(
                    //                    (int) Math.floor(Double.parseDouble
                    //                    (mResultEditText.getText().toString()))));
                    return;
                }
                goTosaomapay();
                break;
            case R.id.rl_member:
                if(mResultEditText.getText().toString().contains("−") || mResultEditText.getText().toString().equals("0")) {
                    ToastUtils.showToast(this, "交易金额不能小于0");
                    return;
                }
                if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 1000000f) {
                    ToastUtils.showToast(this, "金额不能大于一百万");
                    //                    ToastUtils.showToast(this, String.valueOf(
                    //                    (int) Math.floor(Double.parseDouble
                    //                    (mResultEditText.getText().toString()))));
                    return;
                }
                gotoHuiyuanpay();
                break;
            //银联收款
            case R.id.rl_union:
                if(TextUtils.isEmpty(mResultEditText.getText().toString()) || mResultEditText.getText().toString().contains("−") || mResultEditText.getText().toString().equals("0") ) {
                    ToastUtils.showToast(this, "交易金额不能小于0");
                    return;
                }
                Log.i("测试",Float.parseFloat(mResultEditText.getText().toString())+"");
                if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 1000000f) {
                    ToastUtils.showToast(this, "金额不能大于一百万");
                    //                    ToastUtils.showToast(this, String.valueOf(
                    //                    (int) Math.floor(Double.parseDouble
                    //                    (mResultEditText.getText().toString()))));
                    return;
                }

                if(Hawk.get(Constants.IS_ACTIVE, false)) {
                    gotoYinLianPay();
                } else {
                    ToastUtils.showToast(this, "银联功能未激活，请联系运营");
                }


                break;
            case R.id.img_back:
                finish();
                break;
            case R.id.bt_cash_pay:

                String realMoneyResult = mResultEditText.getText().toString();
                String realMoneyDetail = mFormulaEditText.getText().toString();
                String realMoney = null;
                if(TextUtils.isEmpty(realMoneyDetail)) {
                    ToastUtils.showToast(this, "请输入金额");
                    return;
                }
                if(TextUtils.isEmpty(realMoneyResult)) {
                    if(realMoneyDetail.contains("+")) {
                        String replace = realMoneyDetail.replace("+", "");
                        realMoney = replace;
                    } else {
                        realMoney = realMoneyDetail;
                    }

                } else {
                    realMoney = realMoneyResult;
                }
                if(realMoneyResult.contains("E")) {
                    ToastUtils.showToast(this, "请输入正确的金额");
                    return;
                }

                if(realMoneyResult.contains(".")) {
                    String[] split = realMoneyResult.split("[.]");
                    if(split[1].length() > 2) {
                        ToastUtils.showToast(this, "输入金额只能精确到分");
                        return;
                    }
                }
                //负数判断
                if(!realMoneyResult.matches("-?[0-9]+.*[0-9]*")) {
                    ToastUtils.showToast(this, "请输入正确的金额");
                    return;
                }

                //大于0的判断
                Double intrealMoneyDetail = parseDouble(realMoney);
                if(intrealMoneyDetail < 0 | intrealMoneyDetail == 0) {
                    ToastUtils.showToast(this, "输入金额必须大于0");
                    return;
                }
                final String money = realMoney;
                new androidx.appcompat.app.AlertDialog.Builder(this)
                        .setTitle("温馨提示")
                        .setMessage("现金收款成功后无法退款,确定收款?")
                        .setPositiveButton("确定", (dialog, which) -> cashPay(money))
                        .setNegativeButton("取消", null)
                        .show();
                break;
        }
    }

    private String getMark() {

        if(TextUtils.isEmpty(etMark.getText().toString())) {
            return "";
        } else {
            return etMark.getText().toString();
        }
    }

    private void gotoYinLianPay() {
        String realMoneyResult = mResultEditText.getText().toString();
        String realMoneyDetail = mFormulaEditText.getText().toString();
        LogUtils.e("goToCashPay", realMoneyResult + "**" + realMoneyDetail);
        String realMoney = null;
        if(TextUtils.isEmpty(realMoneyDetail)) {
            ToastUtils.showToast(this, "请输入金额");
            return;
        }

        if(realMoneyResult.contains("E")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }

        if(realMoneyResult.contains(".")) {
            String[] split = realMoneyResult.split("[.]");
            if(split[1].length() > 2) {
                ToastUtils.showToast(this, "输入金额只能精确到分");
                return;
            }
        }

        //负数判断
        if(!realMoneyResult.matches("-?[0-9]+.*[0-9]*")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }


        if(TextUtils.isEmpty(realMoneyResult)) {
            if(realMoneyDetail.contains("+")) {
                String replace = realMoneyDetail.replace("+", "");
                realMoney = replace;
            } else {
                realMoney = realMoneyDetail;
            }

        } else {
            realMoney = realMoneyResult;
        }

        //大于0的判断
        Double intrealMoneyDetail = Double.valueOf(realMoney);
        //        Double intrealMoneyDetail = Double.parseDouble(realMoney);
        if(intrealMoneyDetail < 0 | intrealMoneyDetail == 0) {
            ToastUtils.showToast(this, "输入金额必须大于0");
            return;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if(!sdf.format(new Date()).equals(Hawk.get("signTime", "0"))) {
            Log.i("datesdf",sdf.format(new Date())+"-------------");
            Log.i("datesdf",Hawk.get("signTime","0"+"-----------"));
            sign();
        } else {
            Log.i("测试1",Float.parseFloat(realMoney)+"");
            //请求网络 获取订单号
            toYinlianPayMoney(realMoney);
        }

    }

    private void sign() {
        PosSign.Req req = new PosSign.Req();
        sytApi.sendReq(req);
    }

    /**
     * 银联刷卡消费
     *
     * @param
     */
    private void toYinlianPayMoney(String realMoney) {
        if(TextUtils.isEmpty(realMoney)) return;
        rl_union.setClickable(false);
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("payMoney", realMoney);
        Log.i("测试3",Float.parseFloat(realMoney)+"");
        APIRetrofit.getAPIService().getUnionOrderId(RXRequest.getXingPosParams(addParams, CalculatorActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<GetUnionOrderEntity>() {
                    @Override
                    public void onNext(GetUnionOrderEntity entity) {
                        int success = entity.getSuccess();
                        rl_union.setClickable(true);
                        if(success == 1) {
                            globalOrderid = entity.getOrderid();
                            if(TextUtils.isEmpty(entity.getOrderid())) {
                                ToastUtils.showToast(CalculatorActivity.this, "订单获取异常");
                            } else {
                                SwipeCardTrans.Req swipeTrans = new SwipeCardTrans.Req();
                                swipeTrans.amount =
                                        new BigDecimal(realMoney).multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                                swipeTrans.customOrderId = entity.getOrderid();
                                swipeTrans.isPrintTicket = true;
                                sytApi.sendReq(swipeTrans);
                            }
                        } else if(success == -1000) {
                            ToastUtils.showToast(CalculatorActivity.this,
                                    entity.getErrMsg());
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
//                            com.blankj.utilcode.util.ToastUtils.showShortSafe(entity.getErrMsg());
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    LoginActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        rl_union.setClickable(true);
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(CalculatorActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(CalculatorActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(CalculatorActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /**
     * 现金记账
     *
     * @param realMoney
     */
    private void cashPay(String realMoney) {
        if(TextUtils.isEmpty(realMoney)) return;
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("payMoney", realMoney);
        addParams.put("PayType", "0");
        addParams.put("bz", getMark());
        APIRetrofit.getAPIService().CashPay(RXRequest.getXingPosParams(addParams,
                CalculatorActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<CashEntity>() {
                    @Override
                    public void onNext(CashEntity cashEntity) {
                        //                    if (Tools.isAvailable(cashEntity)) return;
                        int success = cashEntity.getSuccess();
                        if(success == 1) {
                            EventBus.getDefault().postSticky(new MessageEvent("sucuss"));
                            Intent intent = new Intent(CalculatorActivity.this,
                                    ResultActivity.class);
                            intent.putExtra("money", realMoney);//订单
                            intent.putExtra("sucess", "1");
                            intent.putExtra("orderid", cashEntity.getOrderid());
                            intent.putExtra("beizhu", getMark());
                            startActivity(intent);
                        } else if(success == -1000) {
                            ToastUtils.showToast(CalculatorActivity.this,
                                    cashEntity.getErrMsg());
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
//                            com.blankj.utilcode.util.ToastUtils.showShortSafe(cashEntity.getErrMsg());
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    LoginActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(CalculatorActivity.this, "网络连接超时",
                                    Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(CalculatorActivity.this, "连接失败",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(CalculatorActivity.this, "检查网络状态",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    private void toXingPos(String payMoneyShuaKa, String orderIdShuKa) {
        //YYYYMMDDhhmmss
        //            Toast.makeText(CalcActivity.this, "orderIdShuKa=="+orderIdShuKa,
        //            Toast.LENGTH_SHORT).show();
        try {
            String stringDate = getStringDate();

            Bundle bundle = new Bundle();
            bundle.putString("msg_tp", "0200");
            bundle.putString("pay_tp", "0");
            bundle.putString("proc_tp", "00");
            bundle.putString("proc_cd", "000000");
            bundle.putString("amt", payMoneyShuaKa);
            bundle.putString("order_no", orderIdShuKa);
            bundle.putString("appid", "sage.lu6gmail.com.posxing");
            bundle.putString("time_stamp", stringDate);
            bundle.putString("print_info", "订单商品明细单价等xxxxxx");
            ComponentName component = new ComponentName("com.newland.caishen", "com" +
                    ".newland.caishen.ui.activity.MainActivity");
            Intent intent = new Intent();
            intent.setComponent(component);
            intent.putExtras(bundle);

            this.startActivityForResult(intent, 1);
        } catch(ActivityNotFoundException e) {
            //TODO:
        } catch(Exception e) {
            //TODO:
            e.printStackTrace();
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("银联问题排查","1"+data.getExtras());
        //xingpos
        if(data == null) return;
        Bundle bundle = data.getExtras();
//        if (bundle.getString("who") == null) return;// TODO: 2018/4/25 0025 11:33 待测试
//         ; ---> 不知道这个判断有什么用，已注释，鹿鸣 2019/1/21
        if(requestCode == 1 && bundle != null) {
            switch(resultCode) {
                // 支付成功
                case Activity.RESULT_OK:
                    onClear();
                    String msgTp = bundle.getString("msg_tp");
                    String proc_cd = bundle.getString("proc_cd");
                    LogUtils.e("empty", proc_cd + "");//银联刷卡 000000
                    if(TextUtils.equals(msgTp, "0210")) {
                        // TODO:
                        try {
                            Toast.makeText(CalculatorActivity.this, "交易成功",
                                    Toast.LENGTH_SHORT).show();
                            String txndetail = bundle.getString("txndetail");
                            Log.e("txndetail", "txndetail==" + txndetail);
                            JSONObject jsonObject = new JSONObject(txndetail);
                            String date =
                                    jsonObject.optString("translocaldate") + jsonObject.optString("translocaltime");
                            String systraceno =
                                    jsonObject.optString("termid") + jsonObject.optString("translocaldate") + jsonObject.optString("systraceno");
//                            String systraceno = jsonObject.optString("systraceno");
                            String cardtype = bundle.getString("cardtype");

                            OrderRecordEntity order = new OrderRecordEntity();
                            order.setType(5);
                            order.setMerchantName(jsonObject.optString("mername"));
                            order.setTermId(jsonObject.optString("termid"));
                            order.setBankAccount(jsonObject.optString("priaccount"));
                            order.setBankCode(jsonObject.optString("acqno"));
                            order.setBankName(jsonObject.optString("iisno"));
                            order.setBatchNo(jsonObject.optString("batchno"));
                            order.setSysTraceNo(jsonObject.optString("systraceno"));
                            order.setReferNo(jsonObject.optString("refernumber"));
                            order.setExpDate(jsonObject.optString("expdate"));
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd " +
                                    "HH:mm:ss");
                            Date time = null;
                            try {
                                time = sdf.parse(jsonObject.optString("translocaldate") + jsonObject.optString("translocaltime"));
                                order.setPayTime(sdf2.format(time));
                            } catch(ParseException e) {
                                e.printStackTrace();
                            }
                            order.setOrderMoney(jsonObject.optString("transamount"));
                            DatabaseManager.getInstance().insert(order);


                            if(TextUtils.isEmpty(bundle.getString("order_no"))) {
                                payShoukuan2(systraceno, 0, cardtype, date,
                                        globalOrderid);
                            } else {
                                payShoukuan2(systraceno, 0, cardtype, date,
                                        bundle.getString("order_no"));
                            }

                        } catch(JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
                // 支付取消
                case Activity.RESULT_CANCELED:
                    String reason = bundle.getString("reason");
                    if(reason != null) {
                        Toast.makeText(CalculatorActivity.this, "交易取消",
                                Toast.LENGTH_SHORT).show();
                        //                        finish();
                    }
                    break;

                default:
                    break;
            }
        }

    }

    private void payShoukuan2(String systraceno, final int i, String cardtype,
                              String date, String orderid) {
        Log.i("银联问题排查","更新银联订单");
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("OutOrderID", systraceno);
        addParams.put("OrderID", orderid);
        //        addParams.put("paytype", "5");
        addParams.put("OrderState", "1");
        addParams.put("time", date);
        addParams.put("cardtype", cardtype);
        APIRetrofit.getAPIService().UpdateUnionPayOrderState(RXRequest.getXingPosParams(addParams, CalculatorActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpdateUnionPayOrderStateEntity>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull UpdateUnionPayOrderStateEntity unionPayOrderStateEntity) {
                        //                        if (Tools.isAvailable
                        //                        (unionPayOrderStateEntity)) return;
                        int success = unionPayOrderStateEntity.getSuccess();
                        if(success == 1) {
                            num = "";
                            mFormulaEditText.getEditableText().clear();
                            //                            mFormulaEditText.setText("0");
                            //                            mResultEditText.setText("0");
                            ToastUtils.showToast(CalculatorActivity.this,
                                    unionPayOrderStateEntity.getErrMsg() + "");
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(unionPayOrderStateEntity.getErrMsg());
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(CalculatorActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(CalculatorActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            ToastUtils.showToast(CalculatorActivity.this,
                                    unionPayOrderStateEntity.getErrMsg() + "");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        LogUtils.e("00", e.toString());
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int f = i + 1;
                                if(f < 5) {
                                    //请求前停止200ms
                                    SystemClock.sleep(200);
                                    payShoukuan2(systraceno, f, cardtype, date, orderid);
                                    Log.d("tag" + f, "走了几次");
                                }
                            }
                        }).start();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    //===================================================================================================

    //=========================================Eventbus引入,收款成功后需要发送到首页消息===============

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if(event.message.equals("sucuss")) {//收款成功
            onClear();
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        try {
            unregisterReceiver(broadcastReceive);
        } catch(Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        // If there's an animation in progress, end it immediately to ensure the state is
        // up-to-date before it is serialized.
        if(mCurrentAnimator != null) {
            mCurrentAnimator.end();
        }

        super.onSaveInstanceState(outState);

        outState.putInt(KEY_CURRENT_STATE, mCurrentState.ordinal());
        outState.putString(KEY_CURRENT_EXPRESSION,
                mTokenizer.getNormalizedExpression(mFormulaEditText.getText().toString()));
    }

    private void setState(CalculatorState state) {
        if(mCurrentState != state) {
            mCurrentState = state;

            if(state == CalculatorState.RESULT || state == CalculatorState.ERROR) {
                mDeleteButton.setVisibility(View.GONE);
                mClearButton.setVisibility(View.VISIBLE);
            } else {
                mDeleteButton.setVisibility(View.VISIBLE);
                mClearButton.setVisibility(View.GONE);
            }

            if(state == CalculatorState.ERROR) {
                final int errorColor =
                        getResources().getColor(R.color.calculator_error_color);
                mFormulaEditText.setTextColor(errorColor);
                mResultEditText.setTextColor(errorColor);
                //                getWindow().setStatusBarColor(errorColor);
            } else {
                mFormulaEditText.setTextColor(getResources().getColor(R.color.display_formula_text_color));
                mResultEditText.setTextColor(getResources().getColor(R.color.bg_black));
                //                getWindow().setStatusBarColor(getResources().getColor
                //                (R.color.calculator_accent_color));
            }
        }
    }

    private void finishAndAnimExit() {
        finish();
        Activity activity = this;
        activity.overridePendingTransition(R.anim.anim_exit, R.anim.from_left_toright);
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        // If there's an animation in progress, end it immediately to ensure the state is
        // up-to-date before the pending user interaction is handled.
        if(mCurrentAnimator != null) {
            mCurrentAnimator.end();
        }
    }

    //扫码支付
    private void goTosaomapay() {
        String realMoneyResult = mResultEditText.getText().toString();
        String realMoneyDetail = mFormulaEditText.getText().toString();
        String realMoney = null;
        if(TextUtils.isEmpty(realMoneyDetail)) {
            ToastUtils.showToast(this, "请输入金额");
            return;
        }
        if(TextUtils.isEmpty(realMoneyResult)) {
            if(realMoneyDetail.contains("+")) {
                String replace = realMoneyDetail.replace("+", "");
                realMoney = replace;
            } else {
                realMoney = realMoneyDetail;
            }

        } else {
            realMoney = realMoneyResult;
        }
        if(realMoneyResult.contains("E")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }

        if(realMoneyResult.contains(".")) {
            String[] split = realMoneyResult.split("[.]");
            if(split[1].length() > 2) {
                ToastUtils.showToast(this, "输入金额只能精确到分");
                return;
            }
        }
        //负数判断
        if(!realMoneyResult.matches("-?[0-9]+.*[0-9]*")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }

        //大于0的判断
        Double intrealMoneyDetail = parseDouble(realMoney);
        if(intrealMoneyDetail < 0 | intrealMoneyDetail == 0) {
            ToastUtils.showToast(this, "输入金额必须大于0");
            return;
        }

        Intent intent = new Intent(this, ScanningActivity.class);
        intent.putExtra("beizhu", getMark());
        intent.putExtra(Constants.QRCODE_CAPUTER, Constants.SCANCODECOLLECTION_QR);
        intent.putExtra(Constants.REALMONEY, realMoney);
        startActivity(intent);

    }

    //会员支付
    private void gotoHuiyuanpay() {
        String realMoneyResult = mResultEditText.getText().toString();
        String realMoneyDetail = mFormulaEditText.getText().toString();
        String realMoney = null;
        if(TextUtils.isEmpty(realMoneyDetail)) {
            ToastUtils.showToast(this, "请输入金额");
            return;
        }


        if(TextUtils.isEmpty(realMoneyResult)) {
            if(realMoneyDetail.contains("+")) {
                String replace = realMoneyDetail.replace("+", "");
                realMoney = replace;
            } else {
                realMoney = realMoneyDetail;
            }

        } else {
            realMoney = realMoneyResult;
        }

        if(realMoneyResult.contains("E")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }

        if(realMoneyResult.contains(".")) {
            String[] split = realMoneyResult.split("[.]");
            if(split[1].length() > 2) {
                ToastUtils.showToast(this, "输入金额只能精确到分");
                return;
            }
        }
        //负数判断
        if(!realMoneyResult.matches("-?[0-9]+.*[0-9]*")) {
            ToastUtils.showToast(this, "请输入正确的金额");
            return;
        }
        //大于0的判断
        Double intrealMoneyDetail = parseDouble(realMoney);
        if(intrealMoneyDetail < 0 | intrealMoneyDetail == 0) {
            ToastUtils.showToast(this, "输入金额必须大于0");
            return;
        }

        Intent intent = new Intent(this, ScanningActivity.class);
        intent.putExtra("beizhu", getMark());
        intent.putExtra(Constants.QRCODE_CAPUTER, Constants.MEMBER_PAYMENT_QR);
        intent.putExtra(Constants.REALMONEY, realMoney);
        intent.putExtra("isMember", true);
        startActivity(intent);
        startActivityWithAnim();
    }

    private void startActivityWithAnim() {
        this.overridePendingTransition(R.anim.from_right_toleft, R.anim.anim_exit);
    }

    public void onButtonClick(View view) {
        String text = mFormulaEditText.getText().toString();
        int length = text.length() - 1;
        switch(view.getId()) {
            case R.id.eq:
                num = "";
                //                onEquals();
                break;
            case R.id.del:

                if(!mResultEditText.getText().toString().contains("−") && !mResultEditText.getText().toString().equals("0")) {
                    if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 100000f) {
                        mResultEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, 100);
                    } else {
                        mResultEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, 120);
                    }
                }

                if(num.length() > 0)
                    num = num.substring(0, num.length() - 1);
                if(length > -1 && (text.lastIndexOf("+") == length || text.lastIndexOf(
                        "−") == length || text.lastIndexOf("×") == length)) {
                    num = text.substring(0, length);
                    if(num.lastIndexOf("×") > -1) {
                        num = num.substring(num.lastIndexOf("×") + 1);
                    }
                    if(num.lastIndexOf("+") > -1) {
                        num = num.substring(num.lastIndexOf("+") + 1);
                    }
                    if(num.lastIndexOf("−") > -1) {
                        num = num.substring(num.lastIndexOf("−") + 1);
                    }
                }
                onDelete();
                break;
            case R.id.clr:
            case R.id.clear:
                num = "";
                onClear();
                break;
            case R.id.op_sub:
                if(length == -1) return;
                if(text.lastIndexOf("×") == length && length > -1)
                    mFormulaEditText.setText(text.substring(0, length));
            case R.id.op_add:
            case R.id.op_mul:
                num = "";
                if(text.lastIndexOf(".") == length && length > -1)
                    mFormulaEditText.setText(text.substring(0, length));
            default:
                String a = ((Button) view).getText().toString();
                if(!mResultEditText.getText().toString().contains("−") && !mResultEditText.getText().toString().equals("0")) {
                    if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 100000f) {
                        mResultEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, 100);
                    } else {
                        mResultEditText.setTextSize(TypedValue.COMPLEX_UNIT_PX, 120);
                    }
                    if(!TextUtils.isEmpty(mResultEditText.getText().toString()) && (Float.parseFloat(mResultEditText.getText().toString())) > 1000000f) {
                        ToastUtils.showToast(this, "金额不能大于一百万");
                        //                    ToastUtils.showToast(this, String.valueOf
                        //                    ((int) Math.floor(Double.parseDouble
                        //                    (mResultEditText.getText().toString()))));
                        return;
                    }
                }

                if(num.indexOf(".") > -1) {
                    if(a.equals(".")) return;
                    if(num.length() - num.indexOf(".") > 2) return;
                }
                if(a.equals(".") && num.equals(""))
                    a = "0.";
                if(a.equals("0") && num.indexOf(".") == -1 && !num.equals("")) {
                    double d = Double.parseDouble(num);
                    if(d == 0)
                        return;
                }
                if(!a.equals("+") && !a.equals("−") && !a.equals("×"))
                    num += a;
                mFormulaEditText.append(a);
                break;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        if(view.getId() == R.id.del) {
            onClear();
            return true;
        }
        return false;
    }

    @Override
    public void onEvaluate(String expr, String result, int errorResourceId) {
        if(mCurrentState == CalculatorState.INPUT) {

            LogUtils.e("result1", "result=" + result);
            if(result == null) {
                mResultEditText.setText(result);
                ivQRCode.setImageResource(R.drawable.img_shoukuanma_02);
            } else if(result.length() > 10) {
                ivQRCode.setImageResource(R.drawable.img_shoukuanma);
                mResultEditText.setText(result.substring(0, 9));
            } else if(result.contains(".")) {
                ivQRCode.setImageResource(R.drawable.img_shoukuanma);
                float v = NumUtil.toFloat(result);
                float v1 = NumUtil.formatFloat(v);
                LogUtils.e("result1", "v1=" + v1);
                mResultEditText.setText(v1 + "");
            } else {
                ivQRCode.setImageResource(R.drawable.img_shoukuanma);
                mResultEditText.setText(result);
            }
        } else if(errorResourceId != INVALID_RES_ID) {
            onError(errorResourceId);
        } else if(!TextUtils.isEmpty(result)) {
            LogUtils.e("result2", "result=" + result);
            onResult(result);
        } else if(mCurrentState == CalculatorState.EVALUATE) {
            // The current expression cannot be evaluated -> return to the input state.
            setState(CalculatorState.INPUT);
        }

        mFormulaEditText.requestFocus();
    }

    @Override
    public void onTextSizeChanged(final TextView textView, float oldSize) {
        if(mCurrentState != CalculatorState.INPUT) {
            // Only animate text changes that occur from user input.
            ToastUtils.showToast(CalculatorActivity.this, "输入的状态");
            return;
        }

        // Calculate the values needed to perform the scale and translation animations,
        // maintaining the same apparent baseline for the displayed text.
        final float textScale = oldSize / textView.getTextSize();
        final float translationX =
                (1.0f - textScale) * (textView.getWidth() / 2.0f - textView.getPaddingEnd());
        final float translationY =
                (1.0f - textScale) * (textView.getHeight() / 2.0f - textView.getPaddingBottom());

        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(textView, View.SCALE_X, textScale, 1.0f),
                ObjectAnimator.ofFloat(textView, View.SCALE_Y, textScale, 1.0f),
                ObjectAnimator.ofFloat(textView, View.TRANSLATION_X, translationX, 0.0f),
                ObjectAnimator.ofFloat(textView, View.TRANSLATION_Y, translationY, 0.0f));
        animatorSet.setDuration(getResources().getInteger(android.R.integer.config_mediumAnimTime));
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.start();
    }

    private void onEquals() {
        if(mCurrentState == CalculatorState.INPUT) {
            setState(CalculatorState.EVALUATE);
            mEvaluator.evaluate(mFormulaEditText.getText(), this);
        }
    }

    private void onDelete() {
        // Delete works like backspace; remove the last character from the expression.
        final Editable formulaText = mFormulaEditText.getEditableText();
        final int formulaLength = formulaText.length();
        if(formulaLength > 0) {
            formulaText.delete(formulaLength - 1, formulaLength);
        }
    }

    private void onClear() {
        if(TextUtils.isEmpty(mFormulaEditText.getText())) {
            return;
        }
        num = "";
        mFormulaEditText.getEditableText().clear();
    }

    private void onError(final int errorResourceId) {
        if(mCurrentState != CalculatorState.EVALUATE) {
            // Only animate error on evaluate.
            mResultEditText.setText(errorResourceId);
            return;
        }
        mResultEditText.setText(errorResourceId);
    }

    private void onResult(final String result) {
        // Calculate the values needed to perform the scale and translation animations,
        // accounting for how the scale will affect the final position of the text.
        final float resultScale =
                mFormulaEditText.getVariableTextSize(result) / mResultEditText.getTextSize();
        final float resultTranslationX = (1.0f - resultScale) *
                (mResultEditText.getWidth() / 2.0f - mResultEditText.getPaddingEnd());
        final float resultTranslationY = (1.0f - resultScale) *
                (mResultEditText.getHeight() / 2.0f - mResultEditText.getPaddingBottom()) +
                (mFormulaEditText.getBottom() - mResultEditText.getBottom()) +
                (mResultEditText.getPaddingBottom() - mFormulaEditText.getPaddingBottom());
        final float formulaTranslationY = -mFormulaEditText.getBottom();

        // Use a value animator to fade to the final text color over the course of the
        // animation.
        final int resultTextColor = mResultEditText.getCurrentTextColor();
        final int formulaTextColor = mFormulaEditText.getCurrentTextColor();
        final ValueAnimator textColorAnimator =
                ValueAnimator.ofObject(new ArgbEvaluator(), resultTextColor,
                        formulaTextColor);
        textColorAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mResultEditText.setTextColor((int) valueAnimator.getAnimatedValue());
            }
        });

        final AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                textColorAnimator,
                ObjectAnimator.ofFloat(mResultEditText, View.SCALE_X, resultScale),
                ObjectAnimator.ofFloat(mResultEditText, View.SCALE_Y, resultScale),
                ObjectAnimator.ofFloat(mResultEditText, View.TRANSLATION_X,
                        resultTranslationX),
                ObjectAnimator.ofFloat(mResultEditText, View.TRANSLATION_Y,
                        resultTranslationY),
                ObjectAnimator.ofFloat(mFormulaEditText, View.TRANSLATION_Y,
                        formulaTranslationY));
        animatorSet.setDuration(getResources().getInteger(android.R.integer.config_longAnimTime));
        animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                mResultEditText.setText(result);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                // Reset all of the values modified during the animation.
                mResultEditText.setTextColor(resultTextColor);
                mResultEditText.setScaleX(1.0f);
                mResultEditText.setScaleY(1.0f);
                mResultEditText.setTranslationX(0.0f);
                mResultEditText.setTranslationY(0.0f);
                mFormulaEditText.setTranslationY(0.0f);

                // Finally update the formula to use the current result.
                mFormulaEditText.setText(result);
                setState(CalculatorState.RESULT);

                mCurrentAnimator = null;
            }
        });

        mCurrentAnimator = animatorSet;
        animatorSet.start();
    }

    private enum CalculatorState {
        INPUT, EVALUATE, RESULT, ERROR
    }


}
